﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel;

namespace WcfCGServicesHost
{
    public class CallLogger : IDispatchMessageInspector
    {
        #region Fields

        private static System.Collections.Concurrent.ConcurrentStack<DateTime> callStack = 
            new System.Collections.Concurrent.ConcurrentStack<DateTime>();

        #endregion

        #region Events

        public event EventHandler Busy = null;
        public event EventHandler Idle = null;


        #endregion

        #region Constructors

        public CallLogger()
        {

        }

        #endregion

        #region IDispatchMessageInspector Members

        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            CallLogger.callStack.Push(DateTime.Now);
            if (this.Busy != null)
                this.Busy(this, EventArgs.Empty);

            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            DateTime lastTime = DateTime.MinValue;
            if (CallLogger.callStack.TryPop(out lastTime)
                && this.Idle != null)
                this.Idle(this, EventArgs.Empty);
        }

        #endregion
    }
}
